import styles from "@/styles/Question.module.scss";
import PageWrapper from "@/components/PageWrapper";
import { getQuestionById } from "@/service/question";
import { getComponent } from "@/components/QuestionComponents";

type PropsType = {
  errno: number;
  data?: {
    _id: string;
    title: string;
    desc?: string;
    css?: string;
    js?: string;
    isPublished: boolean;
    isDeleted: boolean;
    componentList: any[];
  };
  msg?: string;
};

export default function Question(props: PropsType) {
  const { errno, data, msg = "" } = props;

  if (errno !== 0) {
    return (
      <PageWrapper title="错误">
        <h1>错误</h1>
        <p>{msg}</p>
      </PageWrapper>
    );
  }

  const {
    _id,
    title = "",
    desc = "",
    isDeleted,
    isPublished,
    componentList = [],
  } = data || {};

  if (isDeleted) {
    return (
      <PageWrapper title={title} desc={desc}>
        <h1>{title}</h1>
        <p>该问卷已经被删除</p>
      </PageWrapper>
    );
  }

  if (!isPublished) {
    return (
      <PageWrapper title={title} desc={desc}>
        <h1>{title}</h1>
        <p>该问卷尚未发布</p>
      </PageWrapper>
    );
  }

  return (
    <PageWrapper title={title}>
      <h1 style={{ margin: 0 }}>Question page</h1>
      <form action="/api/answer" method="POST">
        <input type="hidden" name="questionId" defaultValue={_id} />
        {componentList.map((c) => {
          return (
            <div className={styles.componentWrapper} key={c.fe_id}>
              {getComponent(c)}
            </div>
          );
        })}
        <div className={styles.submitBtnContainer}>
          <button type="submit">提交</button>
        </div>
      </form>
    </PageWrapper>
  );
}

export async function getServerSideProps(context: any) {
  const { id = "" } = context.params;

  const data = await getQuestionById(id);

  return {
    props: {
      ...data,
    },
  };
}
